<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="demo-form">
      <el-form-item label="用户名:">
        <el-input placeholder="请输入用户名" v-model="searchName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="seleUser">搜索</el-button>
        <el-button type="primary" @click="resetr">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" @click="addUser">添加</el-button>
    <el-button
      type="danger"
      @click="deleteUserList"
      :disabled="letArr.length > 1 ? false : true"
    >
      批量删除
    </el-button>
    <!-- table数据 -->
    <el-table
      border
      style="margin: 10px 0px"
      :data="userArr"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="#" width="50" type="index"></el-table-column>
      <el-table-column label="id" align="center" prop="id"></el-table-column>
      <el-table-column
        label="用户名字"
        align="center"
        prop="username"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户名称"
        align="center"
        prop="name"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户角色"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" icon="User" @click="role(row)">
            分配角色
          </el-button>
          <el-button type="success" size="small" @click="updataUser(row)">
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定删除${row.username}吗`"
            @confirm="deluser(row)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[1, 3, 5, 8]"
      background
      layout="prev, pager, next, jumper,->,total, sizes"
      :total="total"
      @size-change="handleCurrentChange"
      @current-change="handleCurrentChange"
    />
    <!-- 添加或修改组件 抽屉-->
    <el-drawer v-model="drawer" :title="drawerTitle">
      <template #default>
        <div>
          <el-form label-width="80px" :model="addUserForm" :rules="rules">
            <el-form-item label="用户名字" prop="username">
              <el-input
                placeholder="请输入用户名字"
                v-model="addUserForm.username"
              ></el-input>
            </el-form-item>
            <el-form-item label="用户名称" prop="name">
              <el-input
                placeholder="请输入用户名称"
                v-model="addUserForm.name"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="用户密码"
              prop="password"
              v-if="!addUserForm.id"
            >
              <el-input
                placeholder="请输入用户密码"
                v-model="addUserForm.password"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 分配角色 抽屉 -->
    <el-drawer title="分配角色" v-model="drawer2">
      <template #default>
        <el-form label-width="80px">
          <el-form-item label="用户名：">
            <el-input v-model="userPrame.name" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="角色列表">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="inCheckAllChange"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group v-model="assRole" @change="handleCheckChange">
              <el-checkbox v-for="city in allRole" :label="city" :key="city">
                {{ city.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClickRole">取消</el-button>
          <el-button type="primary" @click="saverole">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  reqAddOrUpdateUser,
  reqAllRole,
  reqRemoveUser,
  reqSelectUser,
  reqSetUserRole,
  reqUserInfo,
} from '@/api/acl/user/inedx'
import type {
  AllRole,
  AllRoleResponseData,
  SetRoleData,
  User,
} from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
import { SettingStore } from '@/stores/SettingStore'
//页面数据
//当前页码
let pageNo = ref<number>(1)
//当前条数
let pageSize = ref<number>(5)
//总条数
let total = ref<number>(40)
//已有用户的信息
let userArr = ref<User[]>([])
//是否显示抽屉
let drawer = ref<boolean>(false)
//分配角色抽屉
let drawer2 = ref<boolean>(false)
let drawerTitle = ref<string>('')
//存储全部职位
let allRole = ref<AllRole>([])
//存储已选择职位
let assRole = ref<AllRole>([])
//批量删除的数组
let letArr = ref<number[]>([])
//全选数值
let checkAll = ref<boolean>(false)
//搜索的用户名
let searchName = ref<string>('')
//控制全选按钮的不确定状态
let inCheckAllChange = ref<boolean>(true)
//顶部的全部复选框的change事件
const handleCheckAllChange = (val: boolean) => {
  assRole.value = val ? allRole.value : []
  inCheckAllChange.value = false
}

//低部的全部复选框的change事件
const handleCheckChange = () => {
  if (assRole.value.length === allRole.value.length) {
    inCheckAllChange.value = false
    checkAll.value = true
  } else {
    inCheckAllChange.value = true
  }
}

//分配角色
let userPrame = reactive<User>({ username: '', name: '', password: '', id: 0 })
//角色的分配职位
let updataUserRole = reactive<SetRoleData>({
  roleIdList: '',
  userId: '',
})
//分配角色按钮的点击事件
const role = async (row: User) => {
  let req: AllRoleResponseData = await reqAllRole(row.id as number)
  if (req.code == 200) {
    allRole.value = req.data.allRolesList
    assRole.value = req.data.assignRoles
  } else if (req.code == 400) {
    ElMessage({
      type: 'error',
      message: req.message,
    })
  }
  drawer2.value = true
  Object.assign(userPrame, row)
}

//添加用户的数据
let addUserForm = reactive<User>({
  username: '',
  name: '',
  password: '',
  id: 0,
})
//添加用户
const addUser = () => {
  drawerTitle.value = '添加用户'
  drawer.value = true
}
//编辑用户
const updataUser = (row: User) => {
  drawerTitle.value = '编辑用户'
  Object.assign(addUserForm, row)
  addUserForm.password = ''
  drawer.value = true
}
//取消或保存
const cancelClick = () => {
  drawer.value = false
  Object.assign(addUserForm, {
    username: '',
    name: '',
    password: '',
    id: 0,
  })
}
//角色抽屉取消
const cancelClickRole = () => {
  drawer2.value = false
  assRole.value = []
}
//保存添加的用户
const save = async () => {
  let req = await reqAddOrUpdateUser(addUserForm)
  if (req.code == 200) {
    getHasUser(addUserForm.id ? pageNo.value : 1)
    drawer.value = false
    ElMessage({
      type: 'success',
      message: addUserForm.id ? '编辑成功' : '添加成功',
    })
    addUserForm = {
      username: '',
      name: '',
      password: '',
      id: 0,
    }
  } else {
    ElMessage({
      type: 'error',
      message: addUserForm.id ? '编辑失败' : '添加失败',
    })
  }
}
//角色保存
const saverole = async () => {
  updataUserRole.userId = userPrame.id as number
  updataUserRole.roleIdList = assRole.value.map((item) => item.id) as number[]
  let req = await reqSetUserRole(updataUserRole)
  if (req.code == 200) {
    getHasUser(pageNo.value)
    drawer2.value = false
    ElMessage({
      type: 'success',
      message: '分配角色成功',
    })
    drawer2.value = false
    getHasUser(pageNo.value)
  } else {
    ElMessage({
      type: 'error',
      message: '分配角色失败',
    })
  }
}
//获取全部已有用户账号信息
const getHasUser = async (page: number = 1, name: string = '') => {
  pageNo.value = page
  let res = await reqUserInfo(page, pageSize.value, name)
  if (res.code == 200) {
    total.value = res.data.total
    userArr.value = res.data.records
  }
}
onMounted(() => {
  getHasUser()
})
//页码变化
const handleCurrentChange = (page: number) => {
  getHasUser(page)
}
//表单校验
const rules = {
  username: [
    {
      required: true,
      message: '请输入用户名字',
      trigger: 'blur',
    },
  ],
  name: [
    {
      required: true,
      message: '请输入用户名称',
      trigger: 'blur',
    },
    {
      pattern: /^[a-zA-Z0-9]{6,}$/,
      message: '至少6位由数字和26个英文字母',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入用户密码',
      trigger: 'blur',
    },
    {
      pattern: /^[a-zA-Z0-9]{6,}$/,
      message: '至少6位由数字和26个英文字母',
      trigger: 'blur',
    },
  ],
}
//删除用户
const deluser = async (row: User) => {
  let req = await reqRemoveUser(row.id as number)
  if (req.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasUser(pageNo.value)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}

const handleSelectionChange = (val: User[]) => {
  letArr.value = val.map((item) => item.id as number)
}
//批量删除
const deleteUserList = async () => {
  console.log(letArr.value)
  let req = await reqSelectUser(letArr.value)
  if (req.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasUser(pageNo.value)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
//搜索
const seleUser = async () => {
  await getHasUser(1, searchName.value)
  searchName.value = ''
}
let settingStore = SettingStore()
const resetr = () => {
  settingStore.refresh = !settingStore.refresh
}
</script>
<style scoped lang="scss">
.demo-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
